# coding:utf-8

import logging
from datetime import datetime
# from multiprocessing import current_process
# import psutil


class Logger:
    """
    说明：
        通过Log().getLogger 获得定制过的logger
        1. 可通过控制台打印
        2. 也可在log目录中生成log.log日志文件
    """
    __exist = False  # 每次新开一个进程都会重新定义一个新的Logger，__class.__exist_flag=False
    instance = None

    def __call__(self, projectdir=None, loggingformat=None, logginglevel=None):
        """
        描述：
        :param projectdir: 
        :param loggingformat: 
        :param logginglevel: 
        :return: 
        示例：
            logger = Logger()(projectdir=" ", loggingformat=" ", logginglevel=" ")
            logger.info("msg")
        """
        self.projectdir = projectdir
        self.loggingformat = loggingformat
        self.logginglevel = logginglevel
        return self.__setAndReturnLogger()

    def __setAndReturnLogger(self):
        if not __class__.__exist:
            __class__.__exist = True
            logger = logging.getLogger()
            # 由于重复调用logging.getLogger()会产生多个相同名称的logger(名称为root)，handler数量会一直累加，导致重复记录日志因此这里需要判断处理。
            if not logger.handlers:
                # 设置Handler选择日志输出方式
                # time = datetime.now().strftime("%Y%m%d_%H%M%S")
                today = datetime.now().strftime("%Y%m%d")
                fh = logging.FileHandler(
                    # filename=(self.projectdir + "\\Log\\log_" + time + ".log"),
                    filename=(self.projectdir + "\\Log\\log_" + today + ".log"),
                    encoding="utf-8",
                )  # 文件输出
                ch = logging.StreamHandler() # 控制台输出
                # Handler添加输出格式
                format = logging.Formatter(self.loggingformat)
                fh.setFormatter(format)
                ch.setFormatter(format)
                # 添加Handler
                logger.addHandler(fh)
                logger.addHandler(ch)
            # 设置日志输出级别
            logger.setLevel(self.logginglevel)
            __class__.instance = logger
        return __class__.instance